package login

import (
	"database/sql"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/jmoiron/sqlx"
)

func main() {
}

type MysqlApi struct {
	UserName string   // 数据库登录用户名
	Password string   // 数据库登录密码
	Host     string   // 数据库登录地址
	Port     int      // 数据库端口
	DbName   string   // 数据库名称
	Charset  string   // 字符编码
	Db       *sqlx.DB // 数据库实例
}
type info struct {
	id          string
	username    string
	Account     string
	creatTime   string
	status      string
	token       string
	phoneNumber string
}

func MysqlConfig() *MysqlApi {
	Login := new(MysqlApi)
	Login.Charset = "utf8"         // 字符编码
	Login.UserName = "root"        // 登录用户
	Login.Port = 3306              // 数据库端口
	Login.Host = "127.0.0.1"       // 数据库登录地址
	Login.Password = "mwx17620351" // 数据库登录密码
	Login.DbName = "liumou"        // 数据库名称
	Arg := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", Login.UserName, Login.Password, Login.Host, Login.Port, Login.DbName, Login.Charset)
	fmt.Println(Arg)
	Db, err := sqlx.Open("mysql", Arg)
	if err != nil {
	}
	Login.Db = Db
	return Login

}

func PasOrAccount(Data map[string]string, c *gin.Context) {
	Account, isAccount := Data["Account"]
	pws, ispws := Data["pws"]
	if !isAccount || !ispws {
		c.JSON(http.StatusOK, gin.H{
			"code": 1,
			"msg":  "ok",
			"data": "账号或者密码错误,请重新输入",
		})
		return
	} else {
		// 连接数据库
		db, err := sql.Open("mysql", "root:mwx17620351@tcp(localhost:3306)/ai")
		if err != nil {
			panic(err)
		}
		sql := fmt.Sprintf("select * from userinfo where Account = '%s' and paswrod = '%s'", Account, pws)

		stm, err := db.Prepare(sql)

		if err != nil {
			fmt.Println("预处理失败", err)
			return
		}
		//3.获取查询结果
		rows, err := stm.Query()
		//判空
		if err != nil || !rows.Next() {
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  "ok",
				"data": "账号或者密码错误,请重新输入",
			})
			return
		} else {
			sql = fmt.Sprintf("select id,username,Account,status,token,phoneNumber,creatTime from userinfo where Account = '%s' and paswrod = '%s'", Account, pws)
			rows, err := db.Query(sql)
			if err := db.Ping(); err != nil {
				fmt.Println("连接失败")
				panic(err)
			}
			if err != nil {
				panic(err.Error())
			}

			for rows.Next() {
				var userinfo info
				err = rows.Scan(&userinfo.id, &userinfo.username, &userinfo.Account, &userinfo.creatTime, &userinfo.status, &userinfo.token, &userinfo.phoneNumber)

				fmt.Println(err, 123123)
				resolveinfo := make(map[string]interface{})
				resolveinfo["username"] = userinfo.username
				resolveinfo["Account"] = userinfo.Account
				resolveinfo["creatTime"] = userinfo.creatTime
				resolveinfo["status"] = userinfo.status
				resolveinfo["token"] = userinfo.token
				resolveinfo["phoneNumber"] = userinfo.phoneNumber
				c.JSON(http.StatusOK, gin.H{
					"code": 1,
					"msg":  "ok",
					"data": resolveinfo,
				})
			}

			defer db.Close()

		}

	}

}
func VerifyAccount() {
	fmt.Println(123)
}
